package cn.sh.library.gmwx.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.spreada.utils.chinese.ZHConverter;

/**
 * 
 * @author chenss
 * 
 */
public class StringUtilC {
	public static void main(String[] args) {
		String uri = "1111;2ddd22;3333;11333333331;";
		System.out.println(getFromIndex(uri, ";", 3));
		System.out.println(uri.substring(0, getFromIndex(uri, ";", 3)));
	}

	public static String getSqlEscape(String oStr) {
		String a = "";
		for (char c : oStr.toCharArray()) {
			a = a + "$" + c;
		}
		return a;
	}

	public static String getNullEmpty(String oStr) {
		if ("null".equals(oStr) || isEmpty(oStr)) {
			return null;
		}
		return oStr;
	}

	// 子字符串modelStr在字符串str中第count次出现时的下标
	public static int getFromIndex(String str, String modelStr, Integer count) {
		// 对子字符串进行匹配
		Matcher slashMatcher = Pattern.compile(modelStr).matcher(str);
		int index = 0;
		// matcher.find();尝试查找与该模式匹配的输入序列的下一个子序列
		while (slashMatcher.find()) {
			index++;
			// 当modelStr字符第count次出现的位置
			if (index == count) {
				break;
			}
		}
		// matcher.start();返回以前匹配的初始索引。
		return slashMatcher.start();
	}

	/**
	 * 繁转简体
	 * 
	 * @param strCht
	 * @return
	 */
	public static String getChs(String strCht) {
		if (isEmpty(strCht)) {
			return "";
		}
		return ZHConverter.getInstance(ZHConverter.SIMPLIFIED).convert(strCht);
	}

	/**
	 * 简转繁体
	 * 
	 * @param strCht
	 * @return
	 */
	public static String getCht(String strChs) {
		if (isEmpty(strChs)) {
			return "";
		}
		return ZHConverter.getInstance(ZHConverter.TRADITIONAL).convert(strChs);
	}
	
	public static String invokeWebApi(String url)
			throws ClientProtocolException, IOException {

		String strRet = "";
		// 创建HttpClient实例
		HttpClient httpclient = new DefaultHttpClient();
		// 创建Get方法实例
		HttpGet httpgets = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpgets);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream instreams = entity.getContent();
			strRet = convertStreamToString(instreams);
			// System.out.println( strRet);
			httpgets.abort();
		}

		return strRet.replace("\n", "");
	}
	
	/**
	 * 从缓冲流读取webapi的数据
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String convertStreamToString(InputStream is)
			throws IOException {
		BufferedReader reader = null;
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * 删除list空项
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List removeEmptyList(List list) {
		List list1 = new ArrayList();
		if (list == null || list.size() <= 0)
			return null;
		// 循环第一层
		for (int i = 0; i < list.size(); i++) {
			// 进入每一个list
			List listi = (List) list.get(i);
			if (listi != null && listi.size() > 0)
				list1.add(listi);
		}

		return list1;
	}

	/**
	 * 导出文件名称中文防止乱码
	 * 
	 * @param oStr
	 * @return
	 */
	public static String encodeUtf8(String oStr) {
		try {
			return URLEncoder.encode(oStr, "UTF8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static boolean hasIntersection(Object from1, Object to1,
			Object from2, Object to2) {
		String dblFrom1 = getString(from1);
		String dblTo1 = getString(to1);
		String dblFrom2 = getString(from2);
		String dblTo2 = getString(to2);
		if ((dblFrom1.compareTo(dblFrom2) >= 0 && dblFrom1.compareTo(dblTo2) <= 0)
				|| (dblTo1.compareTo(dblFrom2) >= 0 && dblTo1.compareTo(dblTo2) <= 0)
				|| (dblFrom1.compareTo(dblFrom2) < 0 && dblTo2
						.compareTo(dblTo2) > 0)) {
			return true;
		}
		return false;
	}

	public static String getRandom(int max, int min) {
		Random random = new Random();
		return String.valueOf(random.nextInt(max) % (max - min + 1) + min);
	}

	public static String leftPad(int len, String str) {
		return leftPad(len, str, "0");
	}

	public static String leftPad(int len, String str, String padStr) {
		while (str.length() < len) {
			str = padStr + str;
		}
		return str;
	}

	public static String getDateFormat(String str) {
		if (str == null) {
			return "";
		}

		if (str.length() > 19) {
			return str.substring(0, 10);
		}

		if (str.length() != 8 || str.length() != 14) {
			return str;
		}
		return str.substring(0, 4) + "-" + str.substring(4, 6) + "-"
				+ str.substring(6, 8);
	}

	public static String getDateTimeFormat(String str) {
		if (str == null) {
			return "";
		}
		if (str.length() != 14) {
			return str;
		}
		return str.substring(0, 4) + "-" + str.substring(4, 6) + "-"
				+ str.substring(6, 8) + " " + str.substring(8, 10) + ":"
				+ str.substring(10, 12);
	}

	public static String indexToStrNoOne(int i) {
		if (i <= 1) {
			return "";
		} else {
			return String.valueOf(i);
		}
	}

	public static String getString(Object obj) {
		if (obj == null) {
			return "";
		} else {

			return obj.toString().trim();
		}
	}

	/**
	 * 取得int数据
	 * 
	 * @param text
	 * @return
	 */
	public static Integer getInt(final String text) {
		if (text == null) {
			return 0;
		} else {
			String str = text.trim().replace("+", "");
			if (text.trim().equals("-0")) {
				str = "0";
			}
			try {
				return (int) Double.parseDouble(str);
			} catch (Exception e) {
				return 0;
			}
		}
	}

	/**
	 * 取得double数据
	 * 
	 * @param text
	 * @return
	 */
	public static Double getDouble(final String text) {
		if (text == null) {
			return 0.0;
		} else {
			String str = text.trim().replace("+", "");
			if (text.trim().equals("-0")) {
				str = "0";
			}
			try {
				return Double.parseDouble(str);
			} catch (Exception e) {
				return 0.0;
			}
		}
	}

	/**
	 * 取得double数据
	 * 
	 * @param text
	 * @return
	 */
	public static Double getDouble(final Object text) {
		if (text == null) {
			return 0.0;
		}
		try {
			return Double.parseDouble(text.toString());
		} catch (Exception e) {
			return 0.0;

		}
	}

	/**
	 * 四十五人，保留小数
	 * 
	 * @param value
	 * @param pointLength
	 * @return
	 */
	public static double Round(double value, Integer pointLength) {
		BigDecimal bg = new BigDecimal(value);
		return bg.setScale(pointLength, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 
	 * @param text
	 *            ：传入数字字符串
	 * @param scale
	 *            ：保留的小数位数
	 * @param round
	 *            ：取小数精度的方式
	 * @return
	 */
	public static BigDecimal getBigDecimal(String text, int scale, int round) {
		if (text == null) {
			return new BigDecimal("0");
		} else {
			try {
				return new BigDecimal(text.trim()).setScale(scale, round);
			} catch (Exception e) {
				return new BigDecimal("0");
			}
		}
	}

	/**
	 * 重载BigDecimal方法，默认保留2位小数
	 * 
	 * @param text
	 * @return
	 */
	public static BigDecimal getBigDecimal(String text) {
		if (text == null) {
			return new BigDecimal("0");
		} else {
			try {
				return new BigDecimal(text.trim()).setScale(2,
						BigDecimal.ROUND_HALF_EVEN);
			} catch (Exception e) {
				return new BigDecimal("0");
			}
		}
	}

	public static long getLong(String text) {
		if (text == null) {
			return 0;
		} else {
			try {
				return Long.parseLong(text);
			} catch (Exception e) {
				return 0;
			}
		}
	}

	/**
	 * 取得Integer数据
	 * 
	 * @param text
	 * @return
	 */
	public static Integer getInteger(final String text) {
		if (text == null) {
			return null;
		} else {
			String str = text.trim().replace("+", "");
			if (text.trim().equals("-0")) {
				str = "0";
			}
			try {
				return (int) Double.parseDouble(str);
			} catch (Exception e) {
				return null;
			}
		}
	}

	/**
	 * 取得Short数据
	 * 
	 * @param text
	 * @return
	 */
	public static Short getShort(final Object text) {
		if (text == null) {
			return null;
		}
		try {
			return Short.valueOf(StringUtilC.getString(text));
		} catch (Exception e) {
			return null;
		}
	}

	public static String getStringWithNull(Object obj) {
		if (obj == null) {
			return null;
		} else {
			return obj.toString();
		}
	}

	public static String substring(Object obj, int from, int to) {
		try {
			String str = getString(obj);
			return str.substring(from, to);
		} catch (Exception e) {
			return "";
		}

	}

	public static String format(String format, Object obj) {
		return String.format(format, getString(obj));
		// String.format("%03d",
		// (Integer.parseInt(bangou.get("SINKO_SUB_NO").toString()) +1));
	}

	public static String leftPad(int len, Object obj) {
		return leftPad(len, "0", obj);
	}

	public static String leftPad(int len, String padStr, Object obj) {
		String oStr = getString(obj);
		StringBuilder str = new StringBuilder("");
		int iPad = len - getString(obj).length();
		if (iPad > 0) {
			for (int i = 0; i < iPad; i++) {
				str.append(padStr);
			}
			str.append(oStr);
			return str.toString();
		}
		return oStr;
	}

	public static boolean isEmpty(Object obj) {
		return getString(obj).isEmpty();
	}

	public static boolean hasEmpty(Object... objs) {
		for (Object obj : objs) {
			if (getString(obj).isEmpty()) {
				return true;
			}
		}
		return false;
	}

	public static boolean containsKey(Map<String, String> map, Object obj) {
		if (map.containsKey(obj)) {
			if (!StringUtilC.isEmpty(map.get(obj))) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static boolean mapIsNull(Map<String, String> map) {
		if (map == null) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean isInteger(Object value) {
		try {
			Integer.parseInt(getString(value));
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	public static boolean isDouble(Object value) {
		try {
			Double.parseDouble(getString(value));
			if (getString(value).contains(".")) {
				return true;
			}
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	public static boolean isNumber(Object value) {
		return isInteger(value) || isDouble(value);
	}

	public static Integer getInteger(Object obj) {
		if (obj == null) {
			return null;
		} else if (isInteger(obj)) {
			return Integer.parseInt(getString(obj));
		} else {
			return null;
		}
	}

	/**
	 * 获取金额逗号分隔
	 * 
	 * @param str
	 *            金额
	 * @return
	 */
	public static String getAmount(String str) {
		if (StringUtilC.isEmpty(str)) {
			return "";
		} else {
			Double dbl = StringUtilC.getDouble(str);
			if (dbl == 0) {
				return "0.00";
			} else {
				NumberFormat formater = new DecimalFormat("###,###.00");
				return formater.format(dbl);
			}
		}
	}

	/**
	 * 
	 * @param outputStream
	 * @return
	 */
	public static String StreamToString(OutputStream outputStream) {
		ByteArrayOutputStream baos = (ByteArrayOutputStream) (outputStream);
		String str = null;
		try {
			str = baos.toString("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * string To byte
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] strToByteArray(String str) {
		if (str == null) {
			return null;
		}
		byte[] byteArray = str.getBytes();
		return byteArray;
	}

	/**
	 * 获取金额逗号分隔
	 * 
	 * @param str
	 *            金额
	 * @return
	 */
	public static String getAmount(double dbStr) {
		if (StringUtilC.isEmpty(dbStr)) {
			return "";
		} else {
			if (dbStr == 0) {
				return "0.00";
			} else {
				NumberFormat formater = new DecimalFormat("###,###.00");
				return formater.format(dbStr);
			}
		}
	}

	/**
	 * 获取金额逗号分隔
	 * 
	 * @param str
	 *            金额
	 * @param fmt
	 *            格式
	 * @return
	 */
	public static String getAmount(String str, String fmt) {
		if (StringUtilC.isEmpty(str)) {
			return "";
		}
		NumberFormat formater = new DecimalFormat(fmt);
		return formater.format(Double.parseDouble(str));
	}

	public static String getExceptionString(Exception ex) {
		StringWriter writer = new StringWriter();
		ex.printStackTrace(new PrintWriter(writer));
		return writer.getBuffer().toString();
	}

	/**
	 * 不足位前面加0
	 * 
	 * @param str
	 * @param lenght
	 *            长度
	 * @returns
	 */
	public static String padLeftZero(Object obj, int lenght) {
		// 获取字符
		String str = StringUtilC.getString(obj);
		while (str.length() < lenght) {
			str = '0' + str;
		}
		return str;
	}

	/**
	 * 判断是否是整数
	 * 
	 * @param numberString
	 * @return
	 */
	public static boolean isNumber(String numberString) {
		String reg = "^-?\\d+$";
		return Pattern.compile(reg).matcher(numberString).find();
	}

	// 过滤特殊字符
	public static String StringFilter(Object str) throws PatternSyntaxException {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		if (isEmpty(str)) {
			return "";
		}
		String mUri = str.toString();
		// 如果是URI格式，直接返回，不过滤
		if (mUri.contains("http://")) {
			return getString(str);
		}
		String regEx = "[`~!@#$%^&*()+|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(mUri);
		return m.replaceAll("").trim();
	}  

	public static Object convertModel(Object bean)
			throws IllegalArgumentException, IllegalAccessException {
		/*
		 * 得到类中的所有属性集合
		 */
		Field[] fs = bean.getClass().getDeclaredFields();
		for (int i = 0; i < fs.length; i++) {
			Field f = fs[i];
			f.setAccessible(true); // 设置些属性是可以访问的
			if (f.getName().equals("serialVersionUID"))
				continue;
			if (f.getType() == String.class) {
				f.set(bean, StringUtilC.StringFilter(f.get(bean)));
			}// 给属性设值
		}
		return bean;
	}

	/**
	 * 判断一某实体类中，所以属性是否为空
	 * 
	 * @param bean
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static boolean isFieldNull(Object bean) {
		boolean ret = true;
		Field[] fields = bean.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				if (!StringUtilC.isEmpty(field.get(bean))) {
					ret = false;
					break;
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

}
